<template>
  <div class="trackInfo" ref="scrollEl">
    <NavBar
      isFixed
      isTransparent
      title="页面PUV"
      :navScorllOffset="60"
      navScorllColor="#FFF"
      :scrollEl="scrollEl"
    />
    <!-- 筛选 -->
    <div class="header">
      <!-- 时间范围 -->
      <van-cell
        class="header-time"
        titleClass="header-time-label"
        valueClass="header-time-value"
        icon="clock-o"
        is-link
        arrow-direction="down"
        title="开始~结束"
        :value="timeStr"
        @click="timeShow = true"
      />
      <van-calendar
        v-model:show="timeShow"
        type="range"
        :show-confirm="false"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onConfirmTime"
      />
      <!-- 其他条件 -->
      <van-dropdown-menu ref="menuRef" swipe-threshold="4">
        <van-dropdown-item
          :title="granularityTitle"
          v-model="granularity"
          :options="granularityList"
        />
        <van-dropdown-item
          :title="statisticalTypeTitle"
          v-model="statisticalType"
          :options="statisticalTypeList"
        />
        <van-dropdown-item title="页面路由" ref="routeItemRef">
          <van-field
            v-model="pagePath"
            is-link
            readonly
            label="页面"
            placeholder="路由选择"
            @click="showPicker = true"
          />
          <van-popup v-model:show="showPicker" round position="bottom">
            <van-picker
              :columns="columns"
              @cancel="showPicker = false"
              @confirm="onConfirmRoutePicker"
            />
          </van-popup>
        </van-dropdown-item>
      </van-dropdown-menu>
    </div>
    <!-- 内容 -->
    <div class="content">
      <!-- 图表展示 -->
      <canvas class="content-chart" id="timeDistributionChart"></canvas>
      <!-- 数据指标 -->
      <div class="content-metrics">
        <div class="content-metrics-title">数据指标</div>
        <div class="content-metrics-label">
          总次数：<span class="content-metrics-value">{{ total }}</span>
        </div>
      </div>
    </div>

    <!-- footer -->
    <div class="footer">
      <van-button
        class="footer-btn"
        type="primary"
        block
        round
        @click="onConfirmRoute"
      >
        查询
      </van-button>
    </div>
  </div>
</template>
<script setup name="inviteFriends">
import { useGlobalStore } from "~~/store/global";
import { trackInfo } from "../../api/log.ts";
import { useDateFormat } from "@vueuse/core";

const globalStore = useGlobalStore();
const scrollEl = ref();
const route = useRoute();
const router = useRouter();
console.log("页面参数:", route.query);

const isloadDone = ref(false); // 三方加载完成
loadScript(
  "https://cdn.jsdelivr.net/npm/chart.js",
  (val) => {
    if (val) isloadDone.value = true;
  },
  true,
  false
);

/****** 开始~结束时间 ******/
const timeStr = ref("xx:xx ~ xx:xx"); // 一定要有默认值
const timeShow = ref(false);
let beginTime = Date.now() - 3 * 24 * 60 * 60 * 1000;
let endTime = Date.now() + 60 * 60 * 1000;
const minDate = new Date(2024, 0, 1);
const maxDate = new Date(endTime + 24 * 60 * 60 * 1000);

nextTick(() => {
  timeStr.value = `${useDateFormat(beginTime, "MM-DD").value}~${
    useDateFormat(endTime, "MM-DD").value
  }`;
  console.log("时间范围 values:", timeStr.value);
});

const onConfirmTime = (values) => {
  console.log("时间范围 values:", values);
  timeShow.value = false;
  beginTime = values[0].getTime();
  endTime = values[1].getTime();
  const startTimeStr = useDateFormat(beginTime, "MM-DD").value;
  const endTimeStr = useDateFormat(endTime, "MM-DD").value;
  console.log(startTimeStr, "时间范围 values:", endTimeStr);

  nextTick(() => {
    timeStr.value = `${startTimeStr}~${endTimeStr}`;
  });
};
/****************** 颗粒度 ******************/
const menuRef = ref(null);
const granularity = ref(1); // 颗粒度
const granularityList = [
  { text: "天", value: 1, granularity: "day" },
  { text: "小时", value: 2, granularity: "hour" },
];
const granularityTitle = computed(() => {
  return granularityList.find((e) => e.value == granularity.value).text;
});

/****************** 统计类型 ******************/
const statisticalType = ref(1); // 统计类型
const statisticalTypeList = [
  { text: "PV", value: 1 },
  { text: "UV", value: 2 },
];
const statisticalTypeTitle = computed(() => {
  return statisticalTypeList.find((e) => e.value == statisticalType.value).text;
});

/****************** 页面路由选择 ******************/
const pageRouteArr = router.getRoutes();
// console.log("router:", pageRouteArr);
const showPicker = ref(false); // 展示路由选择
const pagePath = ref(""); // 路由
const columns = ref([]);
// 初始化数据源
const initRoutePicker = () => {
  // 创建一个 Map，键为 path，值为对象
  const routesMap = new Map([].map((item) => [item.path, item]));
  // 添加新对象的函数
  function addUniqueUsingMap(map, newObj) {
    if (!map.has(newObj.path)) {
      map.set(newObj.path, newObj);
      return true; // 成功添加
    }
    return false; // 添加失败，重复
  }

  pageRouteArr.forEach((e, index) => {
    const path = e.path.replace(/^\/[^\/]+/, "");
    addUniqueUsingMap(routesMap, {
      text: e.name.split("___")[0],
      path,
      value: index,
    });
  });
  // 将 Map 转换回数组（如果需要）
  columns.value = Array.from(routesMap.values());
};
let selectPagePath = "zhj-all"; // 选择的路由; 默认查所有数据
const onConfirmRoutePicker = (val) => {
  console.log("--selectedValues-", val);
  // 1. 隐藏选择路由
  showPicker.value = false;
  // 2. 赋值
  pagePath.value = val.selectedOptions[0].text;
  selectPagePath = val.selectedOptions[0].path;
  // showToast(`当前值: ${pagePath.value}`);
  // 3. 关闭弹窗
  routeItemRef.value.toggle(); // 或者 menuRef.value.close();
};
const routeItemRef = ref();
const onConfirmRoute = () => {
  // 2. 请求数据
  getServeLogRequest();
};
/****************** 获取日志数据 ******************/
const isRequestDone = ref(false); // 请求完成
const pointInfo = ref();
const total = ref(0); // 总次数
const getServeLogRequest = () => {
  if (!selectPagePath) {
    showToast("selectPagePath");
    return;
  }

  trackInfo({
    pageNumber: 1,
    pageSize: 999999,
    path: selectPagePath,
    granularity: granularityList.find((e) => e.value == granularity.value)
      .granularity,
    beginTime,
    endTime,
    statisticalType: statisticalTypeTitle.value,
    isCallList: 1,
  }).then((res) => {
    console.log("获取日志:", res);
    if (res) {
      //
      pointInfo.value = res.pointInfo;
      isRequestDone.value = true;
      total.value = res.total;
      // 生成X轴标签
      const labels = [];
      const hoursCount = Object.values(pointInfo.value);
      if (
        granularityList.find((e) => e.value == granularity.value).granularity ==
        "hour"
      ) {
        Object.keys(pointInfo.value).forEach((key) => {
          labels.push(useDateFormat(Number(key), "DD日HH").value);
        });
      } else {
        Object.keys(pointInfo.value).forEach((key) => {
          labels.push(useDateFormat(Number(key), "MM/DD").value);
        });
      }

      console.log(labels, "--hoursCount--", hoursCount);

      if (!myChart) {
        init(labels, hoursCount);
      } else {
        updateChart(labels, hoursCount);
      }
    }
  });
};

// 示例时间戳数组（单位：毫秒）
let myChart; // 图表对象
// 加载 canva 图表 📊
const init = (labels, hoursCount) => {
  // 获取画布上下文
  const ctx = document.getElementById("timeDistributionChart").getContext("2d");

  // 创建图表
  myChart = new Chart(ctx, {
    type: "line", // 线形图
    data: {
      labels: labels, // X轴标签，每小时一个
      datasets: [
        {
          label: `每${granularity.value == 2 ? "小时" : "天"}出现 ${
            statisticalTypeTitle.value
          } 次数`,
          data: hoursCount, // 每小时的出现次数
          borderColor: "rgba(75, 192, 192, 1)", // 线条颜色
          backgroundColor: "rgba(75, 192, 192, 0.2)", // 填充颜色
          borderWidth: 1, // 线条宽度
        },
      ],
    },
    options: {
      responsive: true, // 使图表响应式.
      maintainAspectRatio: false, // 允许图表不保持宽高比
      scales: {
        x: {
          beginAtZero: true,
          ticks: {
            maxTicksLimit: 14, // 限制X轴标签数量，防止标签过多
          },
        },
        y: {
          beginAtZero: true,
        },
      },
    },
  });
};

const updateChart = (labels, hoursCount) => {
  myChart.data.labels = labels;
  myChart.data.datasets[0].data = hoursCount;
  myChart.data.datasets[0].label = `每${
    granularity.value == 2 ? "小时" : "天"
  }出现 ${statisticalTypeTitle.value} 次数`;
  myChart.update();
};

// watch([isRequestDone, isloadDone], (neweVal) => {
//   if (neweVal[0] && neweVal[1]) init();
// });

onMounted(() => {
  // getServeLogRequest();
  initRoutePicker();
});
</script>

<style lang="scss" scoped>
.inviteFriends {
  position: relative;
  background-color: #e1edfa;
  height: calc(var(--vh, 1vh) * 100);
  overflow-y: scroll;
  overflow-x: hidden;
  padding-bottom: calc(var(--safe-area-inset-bottom) + 110 * 2px);

  &-bg {
    position: absolute;
    top: 0;
    left: 0;
    background: linear-gradient(180deg, #8dc4ff 0%, #c6fafc 75%, #c6fafc 100%);
    width: 100vw;
    height: calc(88 * 2px + 375 * 2px);
  }
  &-contentbg {
    position: relative;
    width: 100vw;
    background-color: #e1edfa;
  }
}
</style>
<style lang="scss" scoped>
.header {
  &-time {
    justify-content: center;
    &-label {
      // flex: inherit !important;
      font-size: 15 * 2px;
      font-weight: 700;
    }
    &-value {
      white-space: nowrap;
      font-size: 14 * 2px;
    }
  }
}
.content {
  padding: 12 * 2px 16 * 2px;
  &-chart {
    // width: 100%;
    height: 360 * 2px !important;
  }
  &-metrics {
    &-title {
      font-size: 18 * 2px;
      color: #333;
      font-weight: 700;
      margin: 10 * 2px 16 * 2px;
      text-align: center;
    }
    &-label {
      font-size: 15 * 2px;
      color: #333;
      font-weight: 590;
    }
    &-value {
      color: #007bff;
    }
  }
}
.footer {
  position: fixed;
  bottom: 0;
  padding-bottom: var(--safe-area-inset-bottom);
  background-color: #fff;
  border-top: 1px solid rgba(115, 119, 128, 0.15);
  width: 100vw;
  padding: 16 * 2px;
  &-btn {
    width: 100%;
  }
}
</style>
